﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Linq;
using ALiteTeam.PackageTracer.Data;
using System.Text;

namespace ALiteTeam.PackageTracer.Core.Impl
{
    public class QuerySvcOp : IQueryService
    {
        /// <summary>
        /// Web API地址模板
        /// </summary>
        private static readonly string uriApiTemplate = "http://api.kuaidi100.com/api?id=f722f6493b0566ad&com={0}&nu={1}&show=0&muti={2}&order={3}";

        /// <summary>
        /// 私有API地址模板
        /// </summary>
#if RELEASE
        private static readonly string selfUriTemplate = "http://www.wpbeta.org/PackageTracer/query/{0}/{1}/{2}";
#else
        private static readonly string selfUriTemplate = "http://localhost:27894/query/{0}/{1}/{2}";
#endif


        /// <summary>
        /// 快递商别名（用于API)
        /// </summary>
        protected string _DeliveryAlias;
        protected bool _IsPrivateAPI;

        public event EventHandler<QueryEventArgs> QuerySummaryCompleted;
        public event EventHandler<QueryEventArgs> QueryDetailsCompleted;

        /// <summary>
        /// 包含的运单信息
        /// </summary>
        public DeliveryOrder Order { get; private set; }

        /// <summary>
        /// 快递商信息操作类
        /// </summary>
        public IDeliveryOperate DeliveryOperator { get; set; }

        /// <summary>
        /// 配置信息操作类
        /// </summary>
        public INetTrafficHandle NetTrafficHandler { get; set; }

        /// <summary>
        /// 异常记录类
        /// </summary>
        public ILogWrite LogWriter { get; set; }

        private QuerySvcOp() { }
        public QuerySvcOp(DeliveryOrder order)
        {
            this.Order = order;

            this.InitializeDependence();
            this.Initialize();
        }

        private void InitializeDependence()
        {
            DeliveryOperator = DeliveryDataOp.Instance;
            LogWriter = new GeneralLogWriter();

            NetTrafficHandler = new NetTrafficHandler();
        }

        private void Initialize()
        {
            var delivery = DeliveryOperator.DeliveryResource.Deliveries.Where(e => e.ID == this.Order.DeliveryID).FirstOrDefault();
            _DeliveryAlias = delivery.Alias;
        }

        public void GetSummary()
        {
            bool isSuccess = true;
            var uri = this.BuildWebUri(false);

            var content = string.Empty;
            var client = new WebClient();
            client.Headers["Accpet"] = "Application/Json";

            client.DownloadStringCompleted += (s, ev) =>
            {
                if (ev.Error == null)
                {
                    content = ev.Result;
                    this.Order.LastSummaryUpdatedTime = DateTime.Now;

                    var count = Encoding.UTF8.GetBytes(content).Length;
                    this.NetTrafficHandler.Increase(count, false);
                }
                else
                {
                    isSuccess = false;
                    // 异常记录后被吃掉
                    this.LogWriter.Write(ev.Error);
                }

                if (this.QuerySummaryCompleted != null)
                {
                    this.QuerySummaryCompleted(this, new QueryEventArgs(content, isSuccess));
                }
            };
            client.DownloadStringAsync(uri);
        }

        public void GetDetails()
        {
            bool isSuccess = true;
            var uri = this.BuildWebUri(true);

            var content = string.Empty;
            var client = new WebClient();
            client.Headers["Accept"] = "application/json";

            client.DownloadStringCompleted += (s, ev) =>
            {
                if (ev.Error == null)
                {
                    content = ev.Result;
                    this.Order.LastDetailsUpdatedTime = DateTime.Now;

                    var count = Encoding.UTF8.GetBytes(content).Length;
                    this.NetTrafficHandler.Increase(count, false);
                }
                else
                {
                    isSuccess = false;
                    // 异常记录后被吃掉
                    this.LogWriter.Write(ev.Error);
                }

                if (this.QueryDetailsCompleted != null)
                {
                    this.QueryDetailsCompleted(this, new QueryEventArgs(content, isSuccess));
                }
            };
            client.DownloadStringAsync(uri);
        }        

        private Uri BuildWebUri(bool isDetails)
        {
            Uri result;

            int flag = isDetails ?  1 : 0;
            string sortType = isDetails ? "asc" : "desc";

            // 顺丰，EMS，申通等应走自有API
            switch (this._DeliveryAlias)
            {
                case "shunfeng":                    
                case "ems":
                    {
                        _IsPrivateAPI = true;
                        string uri = string.Format(selfUriTemplate, this._DeliveryAlias, flag, this.Order.OrderNo);
                        result = new Uri(uri);

                        break;
                    }
                default:
                    {
                        _IsPrivateAPI = false;
                        string uri = string.Format(uriApiTemplate, this._DeliveryAlias, this.Order.OrderNo, flag, sortType);
                        result = new Uri(uri);

                        break;
                    }
            }

            return result;
        }
    }
}
